package com.thorqq.translation.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Utils
{
	public static List<String> readFileByLines(String filename)
	{
		List<String> output = new ArrayList<String>();
		File file = new File(filename);
		if(!file.exists() || !file.canRead())
		{
			Log.e("File not exists or can't be read");
			return output;
		}

		BufferedReader reader = null;
		try
		{
			//System.out.println("以行为单位读取文件内容，一次读一整行：");
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			// 一次读入一行，直到读入null为文件结束
			while ((tempString = reader.readLine()) != null)
			{
				//不含任何内容
				if(tempString.length() == 0)
				{
					continue;
				}
				
				//只有换行、空格、tab这几个字符
				boolean bHasContent = false;
				for(int i = 0; i < tempString.length();i++)
				{
					char c = tempString.charAt(i);
					if(c != '\n' && c != ' ' && c != '\t')
					{
						bHasContent = true;
						break;
					}
				}
				if(!bHasContent)
				{
					continue;
				}
				
				output.add(tempString);
			}
			reader.close();
			
			return output;
		}
		catch (IOException e)
		{
			e.printStackTrace();
			return output;
		}
		finally
		{
			if (reader != null)
			{
				try
				{
					reader.close();
				}
				catch (IOException e1)
				{
				}
			}
		}
	}
	
	public static void writeFileByLines(List<String> content, String filename)
	{
		FileOutputStream out = null;
        try
        {
        	out = new FileOutputStream(new File(filename));
            for (String line : content) 
            {
                out.write(line.getBytes());
                out.write("\r\n\r\n".getBytes());
            }
	        out.close();
        }
        catch (IOException e)
        {
	        e.printStackTrace();
        }
        finally
		{
			if (out != null)
			{
				try
				{
					out.close();
				}
				catch (IOException e1)
				{
				}
			}
		}
	}
}
